import { getProfile } from "@/api/modules/model/profile";
import { getSchema } from "@/api/modules/model/schema";
import { SchemaItem } from "@/components/JsonSchemaForm/interface";
import BasicInfo from "./../../../../components/Sansan/Model/components/BasicInfo";
// import Navigation from "./../../../../components/Sansan/Model/device/Navigation";

import { Device, GatewayType } from "@/api/interface/iot";
import { getDevice, modifyDevice, saveToProduct, syncDevice, syncGetDevice } from "@/api/modules/iot/device";
import { getProduct, syncFromProduct } from "@/api/modules/iot/product";
import PageHeader from "@/components/Frame/PageHeader";
import SaveClearBtn from "@/components/Frame/save-clear-btn";
import JsonView from "@/components/Sansan/Model/develop/PrviewSchemaJson";
import OnlineStatus from "@/components/Sansan/Status/OnlineStatus";
import { productModel } from "@/enums/dictEnum";
import { MessageType } from "@/enums/messageEnum";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import router from "@/routers";
import { AuthBtns, SchemaNodeKey } from "@/utils/constants";
import mittBus from "@/utils/mittBus";
import { confirm, showMsg, showTips } from "@/utils/util";
import { ElMessage } from "element-plus";
import { useRoute } from "vue-router";
import SensorList from "../../../../components/Sansan/Model/device/SensorFormList";
import SaveToProduct from "../../product/components/SaveToProduct";
import BasicDialog from "./../components/basicInfo/basicDialog";
import { ComponentInternalInstance, getCurrentInstance } from "vue";
import { isRootDeptId } from "@/utils/format";
import ModbusConfig from "./components/modbusConfig";
import { saveDeviceConfig } from "@/api/modules/iot/variable";
import DialogBox from "@/components/DialogBox";
import EventLog from "./components/eventLog";

export default defineComponent({
	setup() {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const route = useRoute();

		const schemaInfo = ref<SchemaItem>({});
		provide(SchemaNodeKey.schema, schemaInfo);
		const gatewaySchemaInfo = ref<SchemaItem>({});
		provide(SchemaNodeKey.gatewaySchema, gatewaySchemaInfo);
		const prifileInfo = ref<any>({});
		provide(SchemaNodeKey.profile, prifileInfo);
		const gatewayPrifileInfo = ref<any>({});
		provide(SchemaNodeKey.gatewayProfile, gatewayPrifileInfo);
		const detail = reactive({ detail: { type: GatewayType.Device, location: {} } as Device.ResDeviceInfo });
		provide(SchemaNodeKey.detailInfo, detail);
		const disabledMod = ref(true);
		provide(AuthBtns.disabledMod, disabledMod);
		mittBus.on("refreshDeviceDetail", () => {
			init();
		});
		onBeforeUnmount(() => {
			mittBus.off("refreshDeviceDetail");
		});
		const buttonsList = ref<any[]>([]);
		onMounted(async () => {
			await init();
			// 获取页面按钮权限
			buttonsList.value = await useAuthButtons(AuthBtns.iotDevice);
			disabledMod.value =
				!!isRootDeptId([detail.detail]) || !buttonsList.value.some((item: any) => item.path == AuthBtns.pathMod);
		});
		const init = async () => {
			await initDevice();
			await loadProduct();
			await initProfile();
			await initGatewayProfile();
			await initGatewaySchema();
			await initSchema();
			mittBus.emit("clickRefreshDeviceDetail");
		};
		//初始化设备信息
		const initDevice = async () => {
			let { result, code } = await getDevice({ idSn: route.query.sn });
			if (code == 200) {
				detail.detail = result;
			} else {
				showMsg(proxy?.$t("device_detail.msg.nodata"), MessageType.error);
				if (window.frames.length != parent.frames.length) return;
				timeOut.value = setTimeout(() => {
					router.go(-1);
				}, 3000);
			}
		};
		//未找到设备数据时三秒后返回上级页面
		let timeOut = ref();
		//销毁定时器
		onBeforeUnmount(() => {
			clearInterval(timeOut.value);
			timeOut.value = "";
		});
		const initSchema = async () => {
			const { result, code } = await getSchema({ sn: route.query.sn });
			if (code == 200) schemaInfo.value = result.schema;
		};
		const initProfile = async () => {
			const { result, code } = await getProfile({ idSn: route.query.sn });
			if (code == 200) prifileInfo.value = result;
		};
		const initGatewaySchema = async () => {
			if (detail.detail.gatewaySn && route.query.sn != detail.detail.gatewaySn) {
				const { result, code } = await getSchema({ sn: detail.detail.gatewaySn });
				if (code == 200) gatewaySchemaInfo.value = result.schema;
			} else {
				//网关是当前设备
				gatewaySchemaInfo.value = schemaInfo.value;
			}
		};
		const initGatewayProfile = async () => {
			if (detail.detail.gatewaySn && route.query.sn != detail.detail.gatewaySn) {
				const { result, code } = await getProfile({
					idSn: detail.detail.gatewaySn
					// path: `config.subdevice.${route.query.sn}`
				});
				if (code == 200) gatewayPrifileInfo.value = result;
			} else {
				//网关是当前设备
				gatewayPrifileInfo.value = prifileInfo.value;
			}
		};

		const currNav = ref<string>(SchemaNodeKey.config);
		const currNav1 = ref<string>(SchemaNodeKey.sensor);
		const basicDialog = reactive({
			title: proxy?.$t("device_detail.dialog_title.modify"),
			visible: false
		});
		// const changeNav = (nav: string) => {
		// 	currNav.value = nav;
		// };
		const submitBasic = async () => {
			let { success } = await modifyDevice({ ...detail.detail });
			if (success) {
				ElMessage.success(proxy?.$t("device_detail.elmsg.succcess"));
				basicDialog.visible = false;
				initDevice();
			} else {
				ElMessage.error(proxy?.$t("device_detail.elmsg.fail"));
			}
		};

		//按钮事件
		const handleFn = async (fn: String, data?: any) => {
			switch (fn) {
				case "saveToProduct":
					saveToProductDialog.formData.id = data.sn;
					saveToProductDialog.formData.name = data.name;
					saveToProductDialog.visible = true;
					break;
				case "sync":
					syncDevice({ idSn: data.sn }).then(res => {
						showTips(res.code, proxy?.$t("device_detail.tips.sync"), res.message);
					});
					break;
				case "syncGet":
					syncGetDevice({ idSn: data.sn }).then(res => {
						showTips(res.code, proxy?.$t("device_detail.tips.sync_get"), res.message);
						init();
					});
					break;
				case "syncFromProduct":
					if (!data.productModel) {
						showMsg(proxy?.$t("device_detail.msg.noProduct"), MessageType.error);
						return;
					}
					confirm({ content: proxy?.$t("device_detail.confirm.sync_from_product") }).then(flag => {
						if (!flag) {
							return;
						}
						syncFromProduct({ productModel: data.productModel, sn: data.sn }).then(({ code }) => {
							let ok = showTips(code, proxy?.$t("device_detail.tips.sync_from_product"));
							if (ok) {
								init();
							}
						});
					});
					break;
				case "saveConfig":
					let valid = await ModbusConfigRef.value.submit();
					if (!valid) return;
					let { code, message } = await saveDeviceConfig({
						idSn: data.sn,
						nodePath: "config",
						data: ModbusConfigRef.value.formData
					});
					showTips(code, "保存", message);
					break;
				case "eventLog":
					eventLogVisible.value = true;
					break;
			}
		};
		const saveToProductDialog = reactive<any>({
			visible: false,
			formData: {
				id: "",
				name: "",
				type: GatewayType.Device
			}
		});
		const submitToProduct = async (data: Device.ReqProduct) => {
			data.idSn = data.id;
			let { code, message } = await saveToProduct(data);
			let ok = showTips(code, proxy?.$t("device_detail.tips.submit_product"), message);
			if (ok) saveToProductDialog.visible = false;
		};

		const productInfo = ref<Device.ResProduct>({});
		const loadProduct = async () => {
			let res: any;
			if (detail.detail.productModel) {
				//获取设备产品
				res = await getProduct({
					productModel: detail.detail.productModel
				});
			} else if (detail.detail.gatewaySn == productModel.modbus) {
				//设备没有产品，并且设备是modbus接入，则产品默认为modbus
				res = await getProduct({
					productModel: productModel.modbus
				});
			} else if (detail.detail.gatewaySn == productModel.hmp) {
				//设备没有产品，并且设备是hmp接入，则产品默认为hmp
				res = await getProduct({
					productModel: productModel.hmp
				});
			}
			productInfo.value = res?.result || {};
		};
		const ModbusConfigRef = ref();
		const eventLogVisible = ref(false);
		return () => {
			return (
				<div class="minBox" style="width:100%;height:100%">
					<DialogBox v-model:visible={eventLogVisible.value} width={"80%"} title="事件日志" hideFooter>
						<EventLog detail={detail.detail} />
					</DialogBox>
					<PageHeader
						class="leading-6"
						showBackText={false}
						v-slots={{
							operate: () => {
								return (
									<>
										<el-button class="iconfont iconsave" onClick={() => handleFn("saveConfig", detail.detail)}>
											保存
										</el-button>
										<el-button class="iconfont iconfile-text" onClick={() => handleFn("eventLog", detail.detail)}>
											事件日志
										</el-button>
										{buttonsList.value
											.filter(
												(item: any) =>
													item.path != AuthBtns.pathMod &&
													item.path != AuthBtns.pathDel &&
													item.path != AuthBtns.pathAdd &&
													item.path != AuthBtns.pathUpdateLocation &&
													item.path != AuthBtns.pathStrangeGroup &&
													item.path != AuthBtns.pathAssignGroup
											)
											.map((item: any) => {
												return (
													<el-button class="iconfont iconbx-skip-next-circle" onClick={() => handleFn(item.path, detail.detail)}>
														{item.menuName}
													</el-button>
												);
											})}
										{!disabledMod.value && <SaveClearBtn v-model={basicDialog.visible} onSubmit={() => submitBasic()} />}
									</>
								);
							}
						}}
					>
						<div>
							<div>{detail.detail.name || "--"}</div>
							<div class="font-thin text-sm">SN：{detail.detail.sn}</div>
						</div>
						<OnlineStatus v-model={detail.detail.onlineStatus} class="ml-4 mr-4" />
						<el-link
							class="iconfont iconbx-sync ml-2"
							type="primary"
							onClick={() => {
								mittBus.emit("clickRefresh");
								init();
							}}
						>
							{proxy?.$t("device_detail.link.refresh")}
						</el-link>
					</PageHeader>

					<SaveToProduct
						title={proxy?.$t("device_detail.dialog_title.savetoproduct")}
						v-model:visible={saveToProductDialog.visible}
						formData={saveToProductDialog.formData}
						onSubmit={(data: Device.ReqProduct) => {
							submitToProduct(data);
						}}
					></SaveToProduct>
					<BasicDialog
						title={basicDialog.title}
						v-model:visible={basicDialog.visible}
						detail={detail.detail}
						onSubmit={submitBasic}
					></BasicDialog>
					<div style="height: calc(100% - 60px);overflow: auto;background: #ffffff;">
						<div class="iot-detail-content">
							{/* 导航分类：基本信息、设备参数、设备模型、设备日志 */}
							{/* <Navigation onChange={val => changeNav(val)} /> */}
							<div class="block-nav flex pl-6 pr-6 h-12 text-base">
								<div
									class={`pl-6 pr-6 item ${currNav.value == SchemaNodeKey.config ? "active" : ""}`}
									onClick={() => {
										currNav.value = SchemaNodeKey.config;
									}}
								>
									<div class={`mr-1 iconfont iconbx-hdd`}></div>
									设备配置
								</div>
								<div
									class={`pl-6 pr-6 item ${currNav.value == SchemaNodeKey.basic ? "active" : ""}`}
									onClick={() => {
										currNav.value = SchemaNodeKey.basic;
									}}
								>
									<div class={`mr-1 iconfont iconbx-detail`}></div>
									基本信息
								</div>
							</div>
							<div class="bg-white">
								{/*基本信息*/}
								{currNav.value == SchemaNodeKey.basic ? <BasicInfo type={GatewayType.Device} onSubmit={submitBasic} /> : null}
								{/*设备配置信息--接入地址、接入端口*/}
								{currNav.value == SchemaNodeKey.config ? <ModbusConfig ref={ModbusConfigRef} detail={prifileInfo.value} /> : null}
							</div>
							{currNav.value == SchemaNodeKey.config ? (
								<>
									<div class="block-nav flex pl-6 pr-6 h-12 text-base">
										<div
											class={`pl-6 pr-6 item ${currNav1.value == SchemaNodeKey.sensor ? "active" : ""}`}
											onClick={() => {
												currNav1.value = SchemaNodeKey.sensor;
											}}
										>
											<div class={`mr-1 iconfont iconsliders`}></div>
											传感量
										</div>
										<div
											class={`pl-6 pr-6 item ${currNav1.value == SchemaNodeKey.extDevelop ? "active" : ""}`}
											onClick={() => {
												currNav1.value = SchemaNodeKey.extDevelop;
											}}
										>
											<div class={`mr-1 iconfont iconbx-terminal`}></div>
											快照
										</div>
									</div>
									<div class="bg-white">
										{/*设备模型*/}
										{currNav1.value == SchemaNodeKey.sensor ? (
											<SensorList
												columns={[
													{ prop: "operation", label: "操作", type: "", width: 100 },
													{ prop: "key", label: "变量标识", align: "left" },
													{ prop: "label", label: "变量名称", align: "left" },
													{ prop: "paramRead", label: "地址类型" },
													{ prop: "paramOffset", label: "地址偏移" },
													{ prop: "configType", label: "数据类型" },
													{ prop: "paramAccess", label: "读写状态" },
													{ prop: "paramTags", label: "变量标签" },
													{ prop: "data", label: "变量值" },
													{ prop: "more", label: "更多", width: 240 }
												]}
											/>
										) : null}
										{/*模型定义*/}
										{currNav1.value == SchemaNodeKey.extDevelop ? <JsonView type={GatewayType.Device} /> : null}
									</div>
								</>
							) : (
								""
							)}
						</div>
					</div>
				</div>
			);
		};
	}
});
